<template>
    <div>
        <el-card>
            <el-container>
                <el-header v-text="msg"></el-header>
                <el-container>
                    <el-main>
                        <el-row>
                            <el-col :span="2">接收</el-col>
                            <el-col :span="22">
                                <el-input
                                        type="textarea"
                                        :rows="10"
                                        placeholder="接收到的消息"
                                        v-model="msgReceive"
                                        readonly="true">
                                </el-input>
                            </el-col>
                        </el-row>
                    </el-main>
                    <el-main>
                        <el-row>
                            <el-col :span="2">
                                待发送
                            </el-col>
                            <el-col :span="22">
                                <el-input
                                        type="textarea"
                                        :rows="5"
                                        placeholder="准备发送的消息"
                                        @keyup.enter.native="sendMessage"
                                        v-model="msgSend">
                                </el-input>
                            </el-col>
                        </el-row>
                    </el-main>
                    <el-footer class="left">
                        <el-button type="success" @click="sendMessage">发送</el-button>
                    </el-footer>
                </el-container>
            </el-container>
        </el-card>
    </div>
</template>

<script>
    export default {
        name: 'HelloWorld',
        props: {
            msg: String
        },
        data: () => ({
            textarea: '',
            msgSend: '',
            msgReceive: '',
            browser: '',
            heartBeatPack:{
                "type": "client_heartbeat",
                "data":"PONG"
            },
            // wsPath: "ws://127.0.0.1:9001/ws?cipher=920c4c4647d098c1d1ef86a7d8c20053",
            wsPath: "ws://172.16.20.140:9001/ws?cipher=91a9ac533d915930f68c5950229f5e77",
            socket: "",
        }),
        created() {
            this.initWebSocket();
        },
        mounted() {
            this.browser = this.getBrowser();
        },
        destroyed() {
            this.websock.close() //离开路由之后断开websocket连接
        },
        methods: {
            heartBeatHandler(data){
                const type = JSON.parse(data).type
                if(type === "SERVER_HEARTBEAT_REQUEST") {
                    console.log("[client]收到服务端心跳:" + data)
                    this.sendHeartBeat()
                    return true
                }
                return false
            },
            sendHeartBeat(){
                this.websock.send(JSON.stringify(this.heartBeatPack));
                console.log("[client]回应心跳消息:"+JSON.stringify(this.heartBeatPack))
            },
            getBrowser() {
                let explorer = window.navigator.userAgent.toLowerCase();
                if (explorer.indexOf("msie") >= 0) {
                    let ver = explorer.match(/msie ([\d.]+)/)[1];
                    return {name: "IE", version: ver};
                } else if (explorer.indexOf("firefox") >= 0) {
                    let ver = explorer.match(/firefox\/([\d.]+)/)[1];
                    return {name: "Firefox", version: ver};
                } else if (explorer.indexOf("chrome") >= 0) {
                    let ver = explorer.match(/chrome\/([\d.]+)/)[1];
                    return {name: "Chrome", version: ver};
                } else if (explorer.indexOf("opera") >= 0) {
                    let ver = explorer.match(/opera.([\d.]+)/)[1];
                    return {name: "Opera", version: ver};
                } else if (explorer.indexOf("Safari") >= 0) {
                    let ver = explorer.match(/version\/([\d.]+)/)[1];
                    return {name: "Safari", version: ver};
                }

                return {name: "Other", version: "1.0.0"};
            },
            sendMessage() {
                this.websocketSend(this.msgSend)
                this.msgSend = "";
            },
            initWebSocket() { //初始化weosocket
                console.log("准备连接websocket...")
                this.websock = new WebSocket(this.wsPath);
                this.websock.onmessage = this.websocketOnMessage;
                this.websock.onopen = this.websocketOnOpen;
                this.websock.onerror = this.websocketOnError;
                this.websock.onclose = this.websocketClose;
            },
            websocketOnOpen() { //连接建立之后执行send方法发送数据
                let actions = {
                    "account": "chentl",
                    "userId": "24",
                    "userIdentity":"gov",
                    "type": "client_authorization",
                    "timestamp": new Date().getTime(),
                    "clientInfo": {
                        "channel": "browser",
                        "osVersion": this.browser.version,
                        "device": this.browser.name
                    }
                };
                this.wsAuthorize(actions);
            },
            websocketOnError() {//连接建立失败重连
                let _that = this;
                setInterval(function () {
                    _that.initWebSocket();
                }, 10000)
            },
            websocketOnMessage(e) { //数据接收
                if(this.heartBeatHandler(e.data))return;
                console.log("[client]服务端发来消息:" + e.data)
                this.msgReceive += e.data

            },
            wsAuthorize(data) {
                try {
                    console.log("[client]socket注册中...")
                    this.websock.send(JSON.stringify(data));
                    console.log("[client]socket注册成功✅")
                } catch (e) {
                    console.error("[client]socket注册失败❌")
                }

            },
            websocketSend(data) {//
                if (data === "" || data ==="\n") {
                    this.$message.warning("发送的消息不能为空！")
                    return;
                }

                console.log("[client]消息:" + data + "已发往服务端")
                let message = {
                    "account": "chentl",
                    "userId": "24",
                    "theme":"COUNT_UNREAD_MSG_901",
                    "type": "print_theme",
                    "data": {
                        "content": data
                    },
                    "timestamp": new Date().getTime(),
                    "clientInfo": {
                        "channel": "browser",
                        "osVersion": this.browser.version,
                        "device": this.browser.name
                    }
                };
                this.websock.send(JSON.stringify(message));
            },
            websocketClose(e) {  //关闭
                console.log('[client]断开连接', e);
                let message = {
                    "account": "chentl",
                    "userId": "24",
                    "type": "client_closed",
                };
                this.websock.send(JSON.stringify(message));
            },
        },
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
